package com.zhb.designmode.structure.agency.dynamic.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {

    private TargetClient target;

    public CglibProxy(TargetClient target) {
        this.target = target;
    }

    public TargetClient getInstance(TargetClient target){
        Enhancer enhancer = new Enhancer();
        //指定父类
        enhancer.setSuperclass(this.target.getClass());
        //指定回调方法
        enhancer.setCallback(this);
        return (TargetClient) enhancer.create();
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("买房前准备");
        Object result = methodProxy.invoke(target, objects);
        System.out.println("买房后装修");
        return result;
    }
}
